package com.yisu.expressway.push;

import com.google.gson.Gson;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.FeedbackCmdMessage;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.igexin.sdk.message.SetTagCmdMessage;
import com.yisu.expressway.application.ExAppLifecycle;
import com.yisu.expressway.login.LoginManager;
import com.yisu.expressway.onedollar.activity.AwardNoticeDlgActivity;
import com.yisu.expressway.onedollar.model.AwardNoticePushObj;
import com.yisu.expressway.utils.HBLog;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;

/**
 * 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息<br>
 * onReceiveMessageData 处理透传消息<br>
 * onReceiveClientId 接收 cid <br>
 * onReceiveOnlineState cid 离线上线通知 <br>
 * onReceiveCommandResult 各种事件处理回执 <br>
 */
public class GetIntentService extends GTIntentService {
    public static final int DELAY_MILLIS = 5 * 1000;
    private final String TAG = GetIntentService.class.getSimpleName();
    private Handler handler = new Handler();


    public GetIntentService() {
    }

    @Override
    public void onReceiveServicePid(Context context, int pid) {
        HBLog.d(TAG, "onReceiveServicePid -> " + pid);
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        String appid = msg.getAppid();
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();
        byte[] payload = msg.getPayload();
        String pkg = msg.getPkgName();
        String cid = msg.getClientId();

        // 第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
        boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid,
                90001);
        HBLog.d(TAG, "call sendFeedbackMessage = " + (result ? "success" : "failed"));

        HBLog.d(TAG, "onReceiveMessageData -> " + "appid = " + appid + "\ntaskid = " + taskid
                + "\nmessageid = " + messageid + "\npkg = " + pkg + "\ncid = " + cid);

        if (payload == null) {
            HBLog.e(TAG, "receiver payload = null");
        } else {
            final String data = new String(payload);
            HBLog.d(TAG, "receiver payload = " + data);
	        try{
		        final AwardNoticePushObj awardNoticePushObj = new Gson().fromJson(filterMsg(data),
			        AwardNoticePushObj.class);
		        if (awardNoticePushObj.type ==1){
			        showDlg(awardNoticePushObj);
			        PushDataManager.getIntance().getAwardNoticePushObjHashMap().put(awardNoticePushObj.objJson.orderId,awardNoticePushObj);
		        }else if (awardNoticePushObj.type ==2){
			        if (! PushDataManager.getIntance().getAwardNoticePushObjHashMap().containsKey(awardNoticePushObj.objJson.orderId)){
				        showDlg(awardNoticePushObj);
				        PushDataManager.getIntance().getAwardNoticePushObjHashMap().put(awardNoticePushObj.objJson.orderId,awardNoticePushObj);
			        }
		        }
	        }catch (Exception e){
		        e.printStackTrace();
	        }



        }

    }

	private void showDlg(final AwardNoticePushObj awardNoticePushObj) {
		if (!ExAppLifecycle.getIntance().isLaunch()){
			HBLog.d(TAG, "not launched");
			if (awardNoticePushObj.type ==1){
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {

						AwardNoticeDlgActivity.launch(getApplicationContext(), awardNoticePushObj);
					}
				}, DELAY_MILLIS);
			}else if (awardNoticePushObj.type==2){
				HBLog.d(TAG, "do nothing");
			}
		}else {
			HBLog.d(TAG, "launched");
			handler.post(new Runnable() {
				@Override
				public void run() {

					AwardNoticeDlgActivity.launch(getApplicationContext(), awardNoticePushObj);
				}
			});
		}
	}

	private String filterMsg(String data) {
		if (TextUtils.isEmpty(data)){
			return null;
		}
		int i = data.indexOf("{");

		if (i <0){
			return null;
		}else {
			return data.substring(i);
		}
	}

	@Override
    public void onReceiveClientId(Context context, String clientid) {
        HBLog.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
		if (!TextUtils.isEmpty(clientid)){
			HBLog.d(TAG, "onReceiveClientId -> " + clientid);
			LoginManager.setPushClientId(clientid);
		}

    }

    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
        HBLog.d(TAG, "onReceiveOnlineState -> " + (online ? "online" : "offline"));
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
        HBLog.d(TAG, "onReceiveCommandResult -> " + cmdMessage);

        int action = cmdMessage.getAction();

        if (action == PushConsts.SET_TAG_RESULT) {
            setTagResult((SetTagCmdMessage) cmdMessage);
        } else if ((action == PushConsts.THIRDPART_FEEDBACK)) {
            feedbackResult((FeedbackCmdMessage) cmdMessage);
        }
    }

    private void setTagResult(SetTagCmdMessage setTagCmdMsg) {
        String sn = setTagCmdMsg.getSn();
        String code = setTagCmdMsg.getCode();

        String text = "设置标签失败, 未知异常";
        switch (Integer.valueOf(code)) {
            case PushConsts.SETTAG_SUCCESS:
                text = "设置标签成功";
                break;

            case PushConsts.SETTAG_ERROR_COUNT:
                text = "设置标签失败, tag数量过大, 最大不能超过200个";
                break;

            case PushConsts.SETTAG_ERROR_FREQUENCY:
                text = "设置标签失败, 频率过快, 两次间隔应大于1s且一天只能成功调用一次";
                break;

            case PushConsts.SETTAG_ERROR_REPEAT:
                text = "设置标签失败, 标签重复";
                break;

            case PushConsts.SETTAG_ERROR_UNBIND:
                text = "设置标签失败, 服务未初始化成功";
                break;

            case PushConsts.SETTAG_ERROR_EXCEPTION:
                text = "设置标签失败, 未知异常";
                break;

            case PushConsts.SETTAG_ERROR_NULL:
                text = "设置标签失败, tag 为空";
                break;

            case PushConsts.SETTAG_NOTONLINE:
                text = "还未登陆成功";
                break;

            case PushConsts.SETTAG_IN_BLACKLIST:
                text = "该应用已经在黑名单中,请联系售后支持!";
                break;

            case PushConsts.SETTAG_NUM_EXCEED:
                text = "已存 tag 超过限制";
                break;

            default:
                break;
        }

        HBLog.d(TAG, "settag result sn = " + sn + ", code = " + code + ", text = " + text);
    }

    private void feedbackResult(FeedbackCmdMessage feedbackCmdMsg) {
        String appid = feedbackCmdMsg.getAppid();
        String taskid = feedbackCmdMsg.getTaskId();
        String actionid = feedbackCmdMsg.getActionId();
        String result = feedbackCmdMsg.getResult();
        long timestamp = feedbackCmdMsg.getTimeStamp();
        String cid = feedbackCmdMsg.getClientId();

        HBLog.d(TAG,
                "onReceiveCommandResult -> " + "appid = " + appid + "\ntaskid = " + taskid
                        + "\nactionid = " + actionid + "\nresult = " + result + "\ncid = " + cid
                        + "\ntimestamp = " + timestamp);
    }

}
